package com.pqtest.api.domain;

import com.pqtest.api.dto.AccountDto;
import com.pqtest.api.entity.TestCategoryEntity;
import org.bouncycastle.crypto.Digest;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import sun.misc.BASE64Encoder;

import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;
import java.util.Random;

@Component
public class AccountDomain {
    //注册
    public AccountDto registerStudent(AccountDto accountDto) throws Exception {
        if(!accountDto.getPassword().equals(accountDto.getRePassword())){
            throw new Exception("密码不一致");
        }
        if(accountDto.getSalt().equals("")){
            accountDto.setSalt(genSalt());
        }
        accountDto.setType(1);
        accountDto.setPassword(pwdHash(accountDto.getPassword(),accountDto.getSalt()));
        return accountDto;
    }
    //更新密码
    public AccountDto updatePassword(AccountDto accountDto,AccountDto existAccountDto) throws Exception {
        if(existAccountDto == null){
            throw new Exception("用户不存在");
        }
        if(!accountDto.getPassword().equals(accountDto.getRePassword())){
            throw new Exception("密码不一致");
        }
        if(accountDto.getSalt().equals("")){
            accountDto.setSalt(existAccountDto.getSalt());
        }
        accountDto.setPassword(pwdHash(accountDto.getPassword(),accountDto.getSalt()));
        return accountDto;
    }
    //设置分类
    public AccountDto updateCategory(AccountDto accountDto,TestCategoryEntity testCategoryEntity) throws Exception {
        if(accountDto == null){
            throw new Exception("无效的用户");
        }
        if(testCategoryEntity == null){
            throw new Exception("分类不存在");
        }
        return accountDto;
    }
    private String genSalt() {
        Random random = new SecureRandom();
        byte[] salt = new byte[16];
        random.nextBytes(salt);
        return new BASE64Encoder().encode(salt);
    }

    private String pwdHash(String pwd,String salt){
        String firstMd5 = DigestUtils.md5DigestAsHex(pwd.getBytes()) + salt;
        return DigestUtils.md5DigestAsHex(firstMd5.getBytes());
    }
}
